package com.spider.admin.scaffold.common;


import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

/**
 * @author xiong.bo
 * @version 1.0
 * @date 2025/3/22 10:59 上午
 */

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

  /**
   * 处理未认证（未传 token 或 token 无效）的情况，会在这里被拦截
   * 抛出统一格式的异常数据结构。
   *
   * @param request
   * @param response
   * @param authException
   * @throws IOException
   */
  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response,
      AuthenticationException authException) throws IOException {

    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    // 自定义返回格式
    Result result = Result.error(
        HttpStatus.UNAUTHORIZED.value(),
        "Unauthorized: Authentication token was missing or invalid.",
        null
    );
    new ObjectMapper().writeValue(response.getOutputStream(), result);
  }
}
